﻿using Api1.Util;
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Api1.Service
{
    /// <summary>
    /// https://github.com/ServiceStack/ServiceStack.OrmLite#dynamic-result-sets
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseService<T>
    {
        public static OrmLiteConnectionFactory dbFactory = new OrmLiteConnectionFactory(
               String.Format("Uid={0};Password={1};Server={2};Port=3306;Database={3};charset=utf8",
                OperateIniFile.ReadIniData("DB","uid","root"),
                OperateIniFile.ReadIniData("DB", "password", ""),                
                OperateIniFile.ReadIniData("DB", "host", "127.0.0.1"),
                OperateIniFile.ReadIniData("DB", "db", "akv2")
                ),
               MySqlDialect.Provider);
        public static OrmLiteConnectionFactory GetDbFactory()
        {
            return dbFactory;
        }
        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static long Insert(T o) {
            if (o == null) {
                return 0;  
            }
            using (var db=dbFactory.Open()) {
               return    db.Insert(o);
            }            
        }
       

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="o"></param>
        public static void  Update(T o) {
            using (var db=dbFactory.Open()) {
                db.Update(o);
            }
        }
        /// <summary>
        /// 保存或者修改
        /// </summary>
        /// <param name="o"></param>
        public static void Save(T o) {
            using (var db =dbFactory.Open()) {
                db.Save(o);
            }
                
        }
        /// <summary>
        /// 单表查询--列表
        /// </summary>
        /// sql ：select * from m_admin
        ///{["id":"1","card_no":"12345"],["id":"1","card_no":"12345"]}
        /// <param name="sql"></param>
        /// <returns></returns>
        public static List<T> Select(String sql) {
            using (var db = dbFactory.Open()) {
                return db.Select<T>(sql);       
            }
        }
        public static List<Dictionary<String, String>> SelectList(String sql) {
            using (var db = dbFactory.Open())
            {
                return db.Select<Dictionary<String, String>>(sql);
            }
        }

        /// <summary>
        /// 单表查询--一列数据
        /// </summary>
        /// <param name="sql">select card_no from m_interface</param>
        /// <returns>{"1231","5698"}</returns>
        public static List<String> SelectColumn(String sql)
        {
            using (var db = dbFactory.Open())
            {
                return db.Select<String>(sql);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql">"select id,create_time from m_admin"</param>
        /// <returns>
        /// List<Dictionary<String,Object>> list=SelectDictionaryList("select id,create_time from m_ad");
        /// if(list==null){
        ///   return;
        /// }
        ///   foreach (var item in list)
        ///     {
        ///        var t = item["create_time"];
        ///       if (!(t == null))
        ///        {
        ///         Console.WriteLine(t.ToString());
        ///         }
        ///        else
        ///        {
        ///             Console.WriteLine("item 为空");
        ///         }
        ///     }
        /// </returns>
        /// Count==0 表示没有结果
        public static List<Dictionary<String, Object>> SelectDictionaryList(String sql) { 
            using (var db = dbFactory.Open()) {
                return db.Select<Dictionary<String, Object>>(sql);
            }
        }

        /// <summary>
        /// 获取KeyValue  主要 查询结果必须只有一条记录        
        /// </summary>
        /// <param name="sql">"select id,card_no from m_admin"</param>
        /// <returns>{[1,"张三],[2,"list"]}</returns>
        /// Count==0 表示没有结果
        public static List<List<Object>> SelectForDictionary(String sql)
        {
            using (var db = dbFactory.Open())
            {
                return db.Select<List<Object>>(sql);
            }
        }
        
        /// <summary>
        /// 判读某个对象是否存在
        /// BaseService<Test>(new {Id=1});
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static Boolean Exist(T o) {
            using (var db=dbFactory.Open()) { 
                return db.Exists<T>(o); 
            }
        }
        /// <summary>
        /// 获取单个对象/字段
        /// db.Single<List<object>>(db.From<Poco>()
        /// .Select("COUNT(*) Total, MIN(Id) MinId, MAX(Id) MaxId"));
        /// db.Scalar<int>("select count(*) from Track")
        /// 
        /// db.Scalar<object>(db.From<Poco>().Select(x => x.Id));
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public static T Scalar(String sql) {
            using (var db=dbFactory.Open()) {
               return  db.Scalar<T>(sql);
            }
        }
        public static Int32 ScalarForInt(String sql)
        {
            using (var db = dbFactory.Open())
            {
                return db.Scalar<Int32>(sql);
            }
        }
        public static String ScalarForString(String sql)
        {
            using (var db = dbFactory.Open())
            {
                return db.Scalar<String>(sql);
            }
        }
        /// <summary>
        /// 单个实体查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>

        public static T Find(String sql) {
            using (var db=dbFactory.Open()) {
                return db.Single<T>(sql);
            }

        }
        /// <summary>
        /// 统计数量
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int Count(String sql) {
            using (var db=dbFactory.Open()) {
                return db.Scalar<int>(sql);
            }         
        }
        /// <summary>
        /// 执行sql
        /// </summary>
        public static void ExcuteSql(String sql) {
            using (var db = dbFactory.Open()) {
                db.ExecuteSql(sql);
            }
        }
        
    }
}
